/**
 * Created by xnr on 20/2/24.
 */

import { router } from '../router';
import axios from 'axios'
import qs from 'qs'
import { Notify, Toast, Dialog } from 'vant';
import store from '../store'

const instance = axios.create({
    // baseURL: 'https://hanyangkeji.top/hy/', // 正式
    //baseURL: 'http://192.168.0.35/fw/', // 测试
	baseURL:'http://124.70.164.30//fw/',
    //baseURL: 'http://192.168.0.96:8889/', //测试地址
    timeout: 10000, // 请求超时时间
    // transformRequest: (params) => {
    // return qs.stringify(params, { arrayFormat: 'repeat' })
    // }
});
var toast = null;
// request拦截器
instance.interceptors.request.use(
    e => {
        e.params = e.params || {}
        e.headers = e.headers || {};
        e.headers['Accept'] = 'application/json';
        // POST传参序列化
        if (e.requestBody == 'body') {
            e.headers['Content-Type'] = 'application/json'
            e.data = JSON.stringify(e.data);
        } else if (e.requestBody == 'formData') {
            e.headers['Content-Type'] = 'multipart/form-data;boundary=' + new Date().getTime()
        } else {
            e.data = qs.stringify(e.data, { arrayFormat: 'repeat' })
        }
        var user = store.getters.get_user
        if (user && user.token) {
            e.headers['Authorization'] = user.token.issuer + ' ' + user.token.token;
        }

        // 自定义加载图标
        // if (e.loading && !toast) {
        //     Toast.allowMultiple();
        //     toast = Toast.loading({
        //         message: '拼命请求中...',
        //         forbidClick: true,
        //         overlay: true,
        //         duration: 0,
        //         loadingType: 'spinner'
        //     });
        // }
        //set 默认值
        return e
    },
    error => ({ status: 0, msg: error.message })
);
// respone拦截器
instance.interceptors.response.use(
    response => {
        const resp = response.data
        setTimeout(function() {
            toast && toast.clear();
            toast = null;
        }, 300);
        if (response.status === 200) {
            //resp.code = 110;
            if (resp.code == 110) {
                Dialog.alert({
                    message: '您登录已过期，请重新登录'
                }).then(() => {
                    router.goTop('login');
                });
            } else {
                return resp
            }
        }
    },
    error => {
        toast && toast.clear();
        toast = null;
        console.log('err' + error) // for debug
    }
)
export default instance